<?php
//用户管理

namespace App\Services\Manage;

use App\Common\CommonConst;
use App\Models\ManageActionLogModel;
use App\Repositories\ManageUsersRepository;
use App\Services\ManageUserService;
use Illuminate\Support\Facades\Auth;

class UserManageService
{

    private static $loginErrMaxNum = 3;

    /**
     * 用户登录
     * @param $username
     * @param $password
     * @return array
     */
    public static function login($username = '', $password = '')
    {
        if (!$username || !$password) {
            return resultError('请输入账号密码');
        }
        //查询用户名
        $userInfo = ManageUserService::getRow([
            'username' => $username,
        ]);
        if (!$userInfo) {
            return resultError('账号有误');
        }
        //        if ($userInfo['login_err_num'] >= self::$loginErrMaxNum) {
        //            return resultError('密码错误错误次数过多，请联系灵析管理员重置密码');
        //        }
        //加密密码
        $encryptPassword = ManageUserService::getEncryptPassword($password, $userInfo['salt']);
        if ($encryptPassword != $userInfo['password']) {
            //记录登录错误次数
            ManageUserService::incrLoginErrNum($userInfo['id']);

            return resultError('密码有误');
        }
        //登录成功，重置错误次数
        ManageUserService::updateLoginErrNum($userInfo['id'], 0);
        //生成密钥
        Auth::setUser($userInfo);
        $token = $userInfo->createToken(CommonConst::GBD_PLATFORM_MANAGE);

        $output = [
            'token'      => $token->plainTextToken,
            'token_type' => 'Bearer',
        ];

        return resultSuccess($output, '登录成功');
    }


    /**
     * 生成随机盐值
     * @param $length
     * @return string
     */
    public static function generateRandomSalt($length = 10)
    {
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $randString = '';
        for ($i = 0; $i < $length; $i++) {
            $randString .= $chars[rand(0, strlen($chars) - 1)];
        }
        return $randString;
    }

    /**
     * 更新密码
     * @param $manageUserId
     * @param $oldPassword
     * @param $newPassword
     * @return array
     */
    public static function updatePassword($manageUserId, $oldPassword, $newPassword)
    {
        if (!$oldPassword || !$newPassword) {
            return resultError('参数缺失');
        }
        $userInfo = ManageUserService::getUsreInfoById($manageUserId);
        if (!$userInfo) {
            return resultError('用户有误');
        }
        $encryptOldPassword = ManageUserService::getEncryptPassword($oldPassword, $userInfo['salt']);
        //验证旧密码
        if ($encryptOldPassword != $userInfo['password']) {
            return resultError('原密码有误');
        }
        //新密码保存
        $res = ManageUserService::updatePassword($userInfo['id'], $newPassword, $userInfo['salt']);
        if (!$res) {
            return resultError('修改失败');
        }
        //记录日志
        ManageActionLogModel::query()
            ->insert([
                'event'          => 'update_user_self_password',
                'event_id'       => Auth::user()->id,
                'desc'           => "用户自己修改密码",
                'data'           => json_encode([
                ]),
                'status'         => 1,
                'manage_user_id' => Auth::user()->id,
            ]);

        return resultSuccess([], '修复成功');
    }

    /**
     * 获取后台用户列表
     * @param $query
     * @param $page
     * @param $pageSize
     * @return array
     */
    public static function getList($query = [], $page = 1, $pageSize = 20)
    {
        $searchQuery = [
            'username' => $query['username'] ?? '',
            'status'   => $query['status'] ?? '',
            'mobile'   => $query['mobile'] ?? '',
            'email'    => $query['email'] ?? '',
        ];
        //预定义输出
        $output = [
            'total'       => 0,
            'totalPage'   => 0,
            'currentPage' => (int) $page,
            'pageSize'    => (int) $pageSize,
            'currentPage' => (int) $page,
            'list'        => 0,
        ];
        $res = ManageUserService::getPageList($searchQuery, $page, $pageSize);
        //拼装输出字段
        $output['total'] = $res['total'] ?? 0;
        $output['totalPage'] = $res['totalPage'] ?? 0;
        $output['list'] = !empty($res['list']) ? self::formatList($res['list']) : [];

        return $output;
    }

    /**
     * 格式化输出
     * @param $list
     * @return array
     */
    public static function formatList($list = [])
    {
        $output = [];
        if (!$list) {
            return [];
        }
        foreach ($list as $val) {
            $item = [
                'id'          => $val['id'],
                'username'    => $val['username'],
                'mobile'      => $val['mobile'],
                'email'       => $val['email'],
                'status'      => $val['status'],
                'status_text' => ManageUsersRepository::$statusList[$val['status']] ?? '',
            ];

            $output[] = $item;
        }

        return $output;
    }

    /**
     * 新增用户
     * @param $id  //用户id，若存在则走修改流程
     * @param $username
     * @param $password
     * @param $mobile
     * @param $email
     * @return array
     */
    public static function save($id, $username, $password, $mobile, $email)
    {
        if ($id) { //修改流程
            $res = self::updateBySave($id, $username, $mobile, $email);
        } else { //新增流程
            $res = self::addBySave($username, $password, $mobile, $email);
        }

        return $res;
    }

    /**
     * 更新用户信息
     * @param $id
     * @param $username
     * @param $password
     * @param $mobile
     * @param $email
     * @return array
     */
    public static function updateBySave($id, $username, $mobile, $email)
    {
        $userInfo = ManageUserService::getRow([
            'id' => $id,
        ]);
        if (!$userInfo) {
            return resultError('用户有误');
        }
        $res = (new ManageUsersRepository())->updateFields($id, [
            'username' => $username,
            'mobile'   => $mobile,
            'email'    => $email,
        ]);
        if (!$res) {
            return resultError('保存失败');
        }

        return resultSuccess([], '保存成功');
    }

    /**
     * 新增用户信息
     * @param $username
     * @param $password
     * @param $mobile
     * @param $email
     * @return array
     */
    public static function addBySave($username, $password, $mobile, $email)
    {
        if (!$password) {
            return resultError('请填写密码');
        }
        $salt = self::generateRandomSalt();
        $encryptPassword = ManageUserService::getEncryptPassword($password, $salt);
        //验证用户名重复
        $userExist = ManageUserService::getTotal([
            'username' => $username,
        ]);
        if ($userExist) {
            return resultError('用户名重复');
        }
        $data = [
            'username' => $username,
            'password' => $encryptPassword,
            'salt'     => $salt,
            'mobile'   => $mobile,
            'email'    => $email,
        ];
        $res = (new ManageUsersRepository())->save($data);
        if (!$res) {
            return resultError('添加失败');
        }

        return resultSuccess([], '添加成功');
    }

    /**
     * 编辑回显信息
     * @param $id
     * @return array
     */
    public static function editShow($id)
    {
        if (!$id) {
            return [];
        }
        $userInfo = ManageUserService::getUsreInfoById($id);
        if (!$userInfo) {
            return resultError('用户有误');
        }
        $output = [
            'id'       => $userInfo['id'],
            'username' => $userInfo['username'],
            'mobile'   => $userInfo['mobile'],
            'email'    => $userInfo['email'],
        ];

        return resultSuccess($output);
    }

    /**
     * 修改用户状态
     * @param $id
     * @param $status
     * @return array
     */
    public static function updateStatus($id, $status)
    {
        if (!$id) {
            return resultError('参数有误');
        }
        $res = (new ManageUsersRepository())->updateFields($id, [
            'status' => $status,
        ]);
        if (!$res) {
            return resultError('修改失败');
        }
        //记录日志
        ManageActionLogModel::query()
            ->insert([
                'event'          => 'update_sub_user_status',
                'event_id'       => $id,
                'desc'           => "修改后台用户状态",
                'data'           => json_encode([
                    'status'  => $status
                ]),
                'status'         => 1,
                'manage_user_id' => Auth::user()->id,
            ]);

        return resultSuccess([], '修改成功');
    }

}
